import React from 'react';
import { Table, Button, Space, Tag, Popconfirm } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { MenuTreeItem } from '../hooks';

interface MenuTableProps {
  menus: MenuTreeItem[];
  loading: boolean;
  onEdit: (menu: MenuTreeItem) => void;
  onDelete: (id: number) => void;
}

// 递归去除children为[]的children属性
function cleanMenus(data: MenuTreeItem[]): MenuTreeItem[] {
  return data.map(item => {
    const newItem = { ...item };
    if (newItem.children && newItem.children.length > 0) {
      newItem.children = cleanMenus(newItem.children);
    } else {
      delete newItem.children;
    }
    return newItem;
  });
}

const MenuTable: React.FC<MenuTableProps> = ({ menus, loading, onEdit, onDelete }) => {
  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => type === 'menu' ? <Tag color="blue">菜单</Tag> : <Tag color="green">按钮</Tag>,
    },
    {
      title: '排序号',
      dataIndex: 'order_num',
      key: 'order_num',
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: MenuTreeItem) => (
        <Space>
          <Button
            size="small"
            type="link"
            icon={<EditOutlined />}
            onClick={() => onEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个菜单吗？"
            onConfirm={() => onDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button size="small" type="link" danger icon={<DeleteOutlined />}>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <Table
      columns={columns}
      dataSource={cleanMenus(menus)}
      loading={loading}
      rowKey="id"
      pagination={false}
      childrenColumnName="children"
      defaultExpandAllRows
    />
  );
};

export default MenuTable; 